﻿using M_Quality.API.Application.Command.QualityPlanCommand;
using M_Quality.Domain;
using M_Quality.Domain.Dto;
using M_Quality.Repository.Interface;
using MediatR;

namespace M_Quality.API.Application.CommandHandler.QualityPlanCommandHandler
{
    /// <summary>
    /// 反填质检方案信息
    /// </summary>
    public class QualityPianByidCommandHandler : IRequestHandler<QualityPianByidCommand, QualityfangDto< Qualityinspection>>
    {
        protected readonly IQualityprogromRepositry IQualityprogromRepositry;
        protected readonly IQualityPlanRepositry IQualityPlanRepositry;
       protected readonly IQualityinspectionRepository IQualityinspectionRepository;

        public QualityPianByidCommandHandler(IQualityprogromRepositry iQualityprogromRepositry, IQualityPlanRepositry iQualityPlanRepositry, IQualityinspectionRepository iQualityinspectionRepository)
        {
            IQualityprogromRepositry = iQualityprogromRepositry;
            IQualityPlanRepositry = iQualityPlanRepositry;
            IQualityinspectionRepository = iQualityinspectionRepository;
        }

        public async Task<QualityfangDto<Qualityinspection>> Handle(QualityPianByidCommand request, CancellationToken cancellationToken)
        {
            var list = from pr in await IQualityprogromRepositry.GetAllAsync()
                       where pr.QualityPlanCode == request.QualityPlanCode
                       join p in await IQualityPlanRepositry.GetAllAsync() on pr.QualityPlanCode equals p.QualityPlanCode
                       join sp in await IQualityinspectionRepository.GetAllAsync()
                       on pr.QualityinspectionId equals sp.QualityinspectionId
                       select new
                       {
                           QualityPlanCode = p.QualityPlanCode,
                           QualityPlanName = p.QualityPlanName,
                           QualityPlanSart = p.QualityPlanSart,
                           QualitygroupId = pr.QualitygroupId,
                           QualityPlanId=p.QualityPlanId,
                           sp
                       };
            var resulit = list.GroupBy(x => new {
                x.QualityPlanId,
                x.QualityPlanCode,
                x.QualityPlanName,
                x.QualityPlanSart,
                x.QualitygroupId,
            }).Select(g => new QualityfangDto<Qualityinspection>
            {
                QualityPlanId=g.Key.QualityPlanId,
                QualityPlanCode = g.Key.QualityPlanCode,
                QualityPlanName = g.Key.QualityPlanName,
                QualityPlanSart = g.Key.QualityPlanSart,
                QualitygroupId = g.Key.QualitygroupId,
                Qualityinspection=g.Select(x=>x.sp).ToList()
            }).FirstOrDefault();
            return resulit;

        }
    }
}
